﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using JobDescOnline.Presentation.Models;
using eq.CoreBase.View;
using eq.CoreBase.Control;

namespace JobDescOnline.Presentation.Controllers
{
    public class JobTitleController : Controller
    {
        //
        // GET: /JobTitle/

        public JobDescDBEntities1 db = new JobDescDBEntities1();

        public ActionResult Index()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            dynamic model = null;
            int total = 0;

            model = JobTitles.RetrieveByFilterAndPage(page, pagesize, sort, direction);
            total = JobTitles.RetrieveByFilter();

            ViewData["Dir"] = direction.ToLower() == "asc" ? "desc" : "asc";

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/JobTitle/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();
            return View(model);
        }

        public ActionResult AjaxTable()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            string sort = !string.IsNullOrEmpty(Request.QueryString["sort"]) ? Request.QueryString["sort"] : "ID";
            string direction = !string.IsNullOrEmpty(Request.QueryString["direction"]) ? Request.QueryString["direction"] : "ASC";

            dynamic model = null;
            int total = 0;

            if (filters.Count > 0)
            {
                model = JobTitles.RetrieveByFilterAndPage(filters, page, pagesize, sort, direction);
                total = JobTitles.RetrieveByFilter(filters);
            }
            else
            {
                model = JobTitles.RetrieveByFilterAndPage(page, pagesize, sort, direction);
                total = JobTitles.RetrieveByFilter();
            }

            if (total > 0) return View(model);
            else return View("Empty");
        }

        public ActionResult AjaxPaging()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            int total = 0;

            if (filters.Count > 0)
            {
                total = JobTitles.RetrieveByFilter(filters);
            }
            else
            {
                total = JobTitles.RetrieveByFilter();
            }

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/JobTitle/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();

            return View();
        }

        //
        // GET: /JobTitle/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /JobTitle/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    string img = System.IO.Path.GetFileName(Request.Files[0].FileName);
                    if (!string.IsNullOrEmpty(img))
                    {
                        img = System.IO.Path.GetFileName(Request.Files[0].FileName);
                        string path = ConfigurationManager.AppSettings["OrgStr"].ToString();
                        HttpPostedFileBase file = Request.Files[0];
                        file.SaveAs(path + img);
                    }

                    JobTitle jobtitle = new JobTitle
                    {
                        Rowstatus = Convert.ToBoolean(collection["Rowstatus"]),
                        DepartmentID = Convert.ToInt32(collection["DepartmentID"]),
                        Description = collection["Description"],
                        MinEducation = collection["MinEducation"],
                        Major = collection["Major"],
                        MinExperience = collection["MinExperience"],
                        WorkingExperience = collection["WorkingExperience"],
                        Specification = collection["Specification"],
                        FunctionalCompetency = collection["FunctionalCompetency"],
                        Challenge = collection["Challenge"],
                        Authority = collection["Authority"],
                        ImageOrganization = img,
                        CreatedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT",
                        CreatedOn = DateTime.Now
                    };

                    db.JobTitles.AddObject(jobtitle);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View();
            }
        }
        
        //
        // GET: /JobTitle/Edit/5
 
        public ActionResult Edit(int id)
        {
            JobTitle jobtitle = db.JobTitles.Single(d => d.ID == id);
            ViewData["ImgOrgPath"] = ConfigurationManager.AppSettings["UrlOrgStr"].ToString() + jobtitle.ImageOrganization;
            return View(jobtitle);
        }

        //
        // POST: /JobTitle/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    string img = System.IO.Path.GetFileName(Request.Files[0].FileName);
                    if (!string.IsNullOrEmpty(img))
                    {
                        string path = ConfigurationManager.AppSettings["OrgStr"].ToString();
                        HttpPostedFileBase file = Request.Files[0];
                        file.SaveAs(path + img);
                    }

                    JobTitle jobtitle = db.JobTitles.First(d => d.ID == id);
                    jobtitle.Rowstatus = Convert.ToBoolean(collection["Rowstatus"]);
                    jobtitle.DepartmentID = Convert.ToInt32(collection["DepartmentID"]);
                    jobtitle.Description = collection["Description"];
                    jobtitle.MinEducation = collection["MinEducation"];
                    jobtitle.Major = collection["Major"];
                    jobtitle.MinExperience = collection["MinExperience"];
                    jobtitle.WorkingExperience = collection["WorkingExperience"];
                    jobtitle.Specification = collection["Specification"];
                    jobtitle.FunctionalCompetency = collection["FunctionalCompetency"];
                    jobtitle.Challenge = collection["Challenge"];
                    jobtitle.Authority = collection["Authority"];
                    if (!string.IsNullOrEmpty(img)) jobtitle.ImageOrganization = img;
                    jobtitle.LastModifiedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    jobtitle.LastModifiedOn = DateTime.Now;

                    db.JobTitles.ApplyCurrentValues(jobtitle);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /JobTitle/Delete/5

        public ActionResult Delete(int id)
        {
            JobTitle jobtitle = db.JobTitles.Single(d => d.ID == id);
            db.JobTitles.DeleteObject(jobtitle);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Combo(FormCollection collection)
        {
            try
            {
                int DepartmentID = Convert.ToInt32(collection["DepartmentID"]);
                ViewData["Name"] = collection["Name"];
                ViewData["ComboJobTitle"] = JobTitles.JobTitleCombo(DepartmentID);
            }
            catch
            {
                return View("Error");
            }

            return View();
        }

        public JsonResult RetrieveData(int id)
        {
            try
            {
                var jobtitle = db.JobTitles.Single(j => j.ID == id);
                JobTitle json = new JobTitle
                {
                    ID = jobtitle.ID,
                    Rowstatus = jobtitle.Rowstatus,
                    DepartmentID = jobtitle.DepartmentID,
                    Description = jobtitle.Description,
                    MinEducation = jobtitle.Description,
                    Major = jobtitle.Major,
                    MinExperience = jobtitle.MinExperience,
                    WorkingExperience = jobtitle.WorkingExperience.Replace("\n", "<br/>"),
                    Specification = jobtitle.Specification.Replace("\n", "<br/>"),
                    FunctionalCompetency = jobtitle.FunctionalCompetency.Replace("\n", "<br/>"),
                    Challenge = jobtitle.Challenge.Replace("\n", "<br/>"),
                    Authority = jobtitle.Authority.Replace("\n", "<br/>"),
                    ImageOrganization = jobtitle.ImageOrganization,
                    CreatedBy = jobtitle.CreatedBy,
                    CreatedOn = jobtitle.CreatedOn,
                    LastModifiedBy = jobtitle.LastModifiedBy,
                    LastModifiedOn = jobtitle.LastModifiedOn
                };

                return Json(json, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message.ToString(), JsonRequestBehavior.AllowGet);
            }
        }
    }
}
